package initization

import (
	"fmt"
	"github.com/go-redis/redis"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
	"weekly-exam-1/config"
	"weekly-exam-1/internal/model/dao"
)

var (
	err error
)

func init() {
	ViperInit()
	MysqlInit()
	RedisInit()
}
func ViperInit() {
	viper.SetConfigFile("D:\\goWork\\weekly-exam-1\\dev.yaml")
	err = viper.ReadInConfig()
	if err != nil {
		fmt.Println("读取失败")
		return
	} else {
		fmt.Println("读取成功")
	}
	err = viper.Unmarshal(&config.AppConfig)
	if err != nil {
		fmt.Println("解析失败")
		return
	} else {
		fmt.Println("解析成功")
	}
}
func MysqlInit() {
	app := config.AppConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", app.User, app.Password, app.Host, app.Port, app.Database)
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	sqlDB, _ := config.DB.DB()

	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)
	if err != nil {
		fmt.Println("数据库连接失败")
		return
	} else {
		fmt.Println("数据库连接成功")
	}
	config.DB.AutoMigrate(&dao.Users{}, &dao.Goods{}, &dao.OwnGoods{})
}
func RedisInit() {
	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     config.AppConfig.Redis.Host,
		Password: config.AppConfig.Redis.Password,
	})
	err = config.Rdb.Ping().Err()
	if err != nil {
		fmt.Println("redis连接失败")
		return
	} else {
		fmt.Println("redis链接成功")
	}
}
